/**
 * 登录及权限认证
 */

var permission, SERVER_ADDRESS = '';//'http://119.97.137.24';

$(function(){
    var path = window.location.pathname;
    if(path != '/' && path.lastIndexOf('login.html') === -1 && path.lastIndexOf('find_pwd.html') === -1)
        checkLogin();
})

/**
 * 字符串参数格式化，参数格式为{0},{1}...
 * 示例：
 * 		"<span>我是{0}</span>".format("张三")
 */
String.prototype.format = function () {
    var reg = /{{(\d+)}}/gm,
        args = arguments;
    return this.replace(reg, function (match, name) {
        return args[~~name];
    });
};

Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "s": this.getMilliseconds()
    }

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}

/**
 * 日期格式化
 */
String.prototype.formatDate = function(format){
    var d= new Date(this.replace(/-/g,"/"));
    return d.format(format||"yyyy-MM-dd");
}

function GetJsonData(settings) {
    var _success = settings.success
    settings.dataType = settings.dataType || 'jsonp';
    settings.type = settings.type || 'post';
    settings.timeout = settings.timeout || 20000;
    settings.url = SERVER_ADDRESS+settings.url;
    settings.xhrFields = {
        withCredentials: true
    };
    settings.crossDomain =  true;
    settings.success = function(data, textStatus, xhr){
        if(data.loginStatus === 0 ){
            window.location.href = "/login.html";
            return;
        }

        if(data.permission === 0 ){
            top.jsdialog('提示','您无权限进行此操作。');
            return;
        }
        if(_success){
            _success(data, textStatus, xhr);
        }
    };

    settings.error = settings.error || function(xhr, textStatus, errorThrown){
            top.jsdialog('提示','操作失败，请刷新或联系武汉智慧校园客服。');
        };

    $.ajax(settings);

}

function cutString(str, toCutLength){
    if(str.length <= toCutLength){
        return str
    }
    else{
        return str.substring(0, toCutLength) + '...'
    }
}

function getQueryString(name) {
    // 匹配以 name开始或者  &name开始的， 以&结尾的的字符串，i这个参数是不区分大小写
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}

/*-------------------------------------------- artdialog 弹出对话框 begin-----------------------------------------------------*/
//弹出简单Dialog窗口
function jsdialog(msgtitle, msgcontent, width, heigth, url, okCallback, cancleCallback) {
    var _width = width ? width : 250;
    var _height = heigth ? heigth : 50;
    var d = top.dialog({
        title: msgtitle,
        content: msgcontent,
        backdropOpacity:0.3,
        width: _width,
        height: _height,
        zIndex: 10000,
        okValue: '确定',
        ok: function () {
            okCallback && okCallback(d);
        },
        onclose: function () {
            if (url) {
                if (url == "back") {
                    history.back(-1);
                } else if (url != "") {
                    location.href = url;
                }
            }
            //执行回调函数
            cancleCallback && cancleCallback();
        }
    }).showModal();

}

function confrimDialog(msg, okCallback, cancleCallback) {
    top.dialog({
        title: '提示',
        content: msg,
        width: 200,
        backdropOpacity:0.3,
        okValue: '确定',
        zIndex: 10000,
        ok: function () {
            okCallback && okCallback();
        },
        cancelValue: '取消',
        cancel: function(){
            cancleCallback && cancleCallback();
        }
    }).showModal();
}
//弹出Dialog窗口, zIndex为10000，防止遮罩挡住
function jsdialogZindex(msgtitle, msgcontent, width, heigth, url, callback) {
    var _width = width ? width : 250;
    var _height = heigth ? heigth : 50;
    var d = top.dialog({
        title: msgtitle,
        content: msgcontent,
        backdropOpacity:0.3,
        width: _width,
        height: _height,
        okValue: '确定',
        zIndex: 10000,
        ok: function () { },
        onclose: function () {
            if (url) {
                if (url == "back") {
                    history.back(-1);
                } else if (url != "") {
                    location.href = url;
                }
            }
            //执行回调函数
            if (callback) {
                callback();
            }
        }
    }).showModal();

}

//confirm 确认框
function confrimDialog(msg, callback, cancleCallback) {
    top.dialog({
        title: '提示',
        content: msg,
        width: 200,
        backdropOpacity:0.3,
        okValue: '确定',
        ok: function () {
            if (callback) {
                callback();
            }
        },
        cancelValue: '取消',
        cancel: function(){
            if(cancleCallback){
                cancleCallback();
            }
        }
    }).showModal();
}

function initGradeAndClass(gradeMap, onClassChange, parentArea){
    var  firstGradeID,
        gradeArr = [],
        classArr = [];

    for(var gradeID in gradeMap){
        var currentGrade = gradeMap[gradeID],
            gradeStr = '<option ';
        if(gradeArr.length == 0){
            firstGradeID = gradeID;
            gradeStr += ' selected="selected" ';
        }

        gradeArr.push(gradeStr+'value="'+gradeID+'">'+currentGrade.gradename+'</option>');
    };

    if(firstGradeID){
        var classMap = gradeMap[firstGradeID].classmap;
        for(var classID in classMap){
            var  currentClass = classMap[classID],
                classStr = '<option gradeID="'+firstGradeID+'" ';
            if(classArr.length === 0){
                classStr += 'selected="selected"';
            }
            classArr.push(classStr + ' value="'+classID+'">'+currentClass.classname+'</option>')
        };

        var gradeSelectElement = parentArea? parentArea.find('.selectGrade'): $('.selectGrade'),
            classSelectElement  = parentArea? parentArea.find('.selectClass'):$('.selectClass');

        gradeSelectElement.on('change', function(){

            var selectedGradeID = $(this).val(),
                currentClassMap = gradeMap[selectedGradeID].classmap,
                flag = true,
                classArr = [];

            for(var classID in currentClassMap){
                var  currentClass = currentClassMap[classID],
                    classStr = '<option gradeID="'+selectedGradeID+'" ';
                if(classArr.length === 0){
                    classStr += 'selected="selected"';
                }
                classArr.push(classStr + ' value="'+classID+'">'+currentClass.classname+'</option>')
            };
            classSelectElement.html(classArr.join(''));
            classSelectElement.trigger('change');
        })

        classSelectElement.on('change', function(){
            var selectedGrade = $(this).children('option:selected');
            if(onClassChange){
                onClassChange(selectedGrade, selectedGrade.attr('gradeid'), selectedGrade.val());
            }
        });

        gradeSelectElement.html(gradeArr.join(""));
        classSelectElement.html(classArr.join(""));
        classSelectElement.trigger('change');
    }
    else{
        jsdialog('提示', '您暂无查看任何班级的数据权限');
    }
}


//function initGradeAndClass(gradeMap, onClassChange, parentArea){
//	var  firstGradeID,
//	    gradeArr = [],
//	    classArr = [];
//
//	for(var gradeID in gradeMap){
//	   var currentGrade = gradeMap[gradeID],
//	   	   gradeStr = '<option ';
//	   if(gradeArr.length == 0){
//		   firstGradeID = gradeID;
//		   gradeStr += ' selected="selected" ';
//	   }
//	   
//	   gradeArr.push(gradeStr+'value="'+gradeID+'">'+currentGrade.gradename+'</option>');
//	   var classMap = currentGrade.classmap;
//	   for(var classID in classMap){
//		   var  currentClass = classMap[classID],
//		   		classStr = '<option gradeID="'+gradeID+'" ';
//		   if(currentClass.gradeid != firstGradeID){
//			   classStr += 'style = "display:none"';
//		   }
//		  
//		   classArr.push(classStr + ' value="'+classID+'">'+currentClass.classname+'</option>')
//	   };
//	};
//	var gradeSelectElement = parentArea? parentArea.find('.selectGrade'): $('.selectGrade'),
//		classSelectElement  = parentArea? parentArea.find('.selectClass'):$('.selectClass');
//	
//	gradeSelectElement.on('change', function(){
//		  var selectedGradeID = $(this).children('option:selected').val();
//		  var flag = true;
//		  classSelectElement.children().each(function(){
//			  if($(this).attr('gradeid') === selectedGradeID){
//				  $(this).show();
//				  if(flag){
//					  $(this).attr('selected', 'selected');
//					  flag = false;
//				  }
//			  }
//			  else{
//				  $(this).hide().removeAttr('selected')
//			  }
//		  })
//		  classSelectElement.trigger('change');
//	})
//	
//	classSelectElement.on('change', function(){
//	   var selectedGrade = $(this).children('option:selected');
//	   if(onClassChange){
//		   onClassChange(selectedGrade, selectedGrade.attr('gradeid'), selectedGrade.val());
//	   }
//	});
//	
//	gradeSelectElement.append(gradeArr.join(""));
//	classSelectElement.append(classArr.join(""));
//	classSelectElement.children('option:first').attr('selected', 'selected');
//	classSelectElement.trigger('change');
//}

function checkLogin(){
    //验证权限
    permission = sessionStorage.getItem('permission');
    if(permission === undefined || permission === null){
        window.location.href = "/login.html";
        return;
    }

    permission = permission.split("#")



    //全局的ajax访问，处理ajax清求时sesion超时  
//    $.ajaxSetup({   
//        complete:function(xhr,textStatus){   
//        	console.log("complete")
//        	//通过XMLHttpRequest取得响应头，loginStatus，
//            var loginStatus = xhr.getResponseHeader("loginStatus")
//    		if(loginStatus === 0 ){
//            	console.log("loginStatus")
//    			window.location.href = "/login.html";
//    			return;
//    		}
//        	
//            var permissionStatus = xhr.getResponseHeader("permission")
//    		if(permissionStatus === 0 ){
//    			console.log("permissionStatus")
//    			window.location.href = "/login.html";
//    			return;
//    		}
//            
//        }   
//    });  

    var accountCookie = $.cookie('account');
    if(accountCookie){
        var accountInfoArr = accountCookie.split("#");
        $(".accountSchoolName").text(decodeURI(accountInfoArr[0]));
        $("#accountName").text(decodeURI(accountInfoArr[1]));
        var photo = accountInfoArr[2];
        if(!photo){
            photo = accountInfoArr[4]?'/images/boy.png': '/images/gril.png';
        }
        $("#accountPhoto").attr('src',  photo);
        $("#accountMobile").text(accountInfoArr[3]);
    }
    else{
        window.location.href = "/login.html";
        return;
    }


    $('.permission').each(function(){
        var permissionUrl = $(this).attr('data-permission');
        if(permissionUrl){
            var toCheckUrls = permissionUrl.split(",");
            if(toCheckUrls){
                var permissionType = $(this).attr("data-permissionType");

                if(checkPermission(toCheckUrls, permissionType)){
                    $(this).show();
                }
                else{
                    $(this).hide();
                }
            }

        }
    })
}

function checkPermission(toCheckUrls, permissionType){
    var flag = false;

    if($.isArray(toCheckUrls)){
        if(toCheckUrls && toCheckUrls.length > 0){
            // 根据权限检查策略检查是否有权访问该url
            if(permissionType === "all"){
                // 安全模式,全部权限检查，检查所有需要认证的url，只要可授权url包含所有要授权url才可认证通过
                for (var i = 0, len = toCheckUrls.length; i < len; i++) {
                    if($.inArray(toCheckUrls[i], permission) === -1){
                        flag = false;
                        break;
                    }
                    flag = true;
                }
            }
            else{
                // 单一权限检查模式，检查所有需要认证的url，只要可授权url包含一个要授权url即可认证通过
                for (var j = 0, len = toCheckUrls.length; j < len; j++) {
                    if ($.inArray(toCheckUrls[j], permission) >= 0) {
                        flag = true;
                        break;
                    }
                }
            }
        }
        return flag;
    }
    else{
        throw new error("要检查的权限url必须是数组");

    }
}